<template>
  <view class="wrapper">
    <!-- 收货信息 -->
    <view class="shipment">
      <!-- 默认不显示 -->
      <view v-if="address" @click="getAddress">
        <view class="dt">收货人:</view>
        <view class="dd meta">
          <text class="name">{{ address.userName }}</text>
          <text class="phone">{{ address.telNumber }}</text>
        </view>
        <view class="dt">收货地址:</view>
        <view class="dd">{{ adds }}</view>
      </view>
      <button @click="getAddress" type="primary" v-else>获取收货地址</button>
    </view>
    <!-- 购物车 -->
    <view class="carts">
      <view class="item">
        <!-- 店铺名称 -->
        <view class="shopname">优购生活馆</view>
        <!-- 购物车中添加的商品 遍历 -->
        <view class="goods" v-for="(cart, i) in carts" :key="cart.goods_id">
          <!-- 商品图片 -->
          <image class="pic" :src="cart.goods_small_logo" />
          <!-- 商品信息 -->
          <view class="meta">
            <view class="name">{{ cart.goods_name }}</view>
            <view class="price">
              <text>￥</text>{{ cart.goods_price }}
              <text>.00</text>
            </view>
            <!-- 加减 -->
            <view class="amount">
              <text class="reduce" @click="changeCount(i, -1)">-</text>
              <input type="number" v-model="cart.goods_count" class="number" />
              <text class="plus" @click="changeCount(i, 1)">+</text>
            </view>
          </view>
          <!-- 选框 -->
          <view class="checkbox" @click="signSel(i)">
            <icon
              type="success"
              size="20"
              :color="cart.goods_checked ? '#ea4451' : '#ccc'"
            ></icon>
          </view>
        </view>
      </view>
    </view>
    <!-- 其它 -->
    <view class="extra">
      <label class="checkall" @click="selAll">
        <icon
          type="success"
          :color="isSelAll ? '#ea4451' : '#ccc'"
          size="20"
        ></icon
        >全选
      </label>
      <view class="total">
        合计:
        <text>￥</text>
        <label>{{ amount }}</label>
        <text>.00</text>
      </view>
      <view @click="createOrder" class="pay">结算({{ seledPrds.length }})</view>
    </view>
  </view>
</template>

<script>
export default {
  data () {
    return {
      // 购物车中数据
      carts: [],
      // 收货地址
      address: null
    }
  },
  watch: {
    carts: {
      deep: true,
      handler () {
        // 存储本地
        uni.setStorageSync("carts", this.carts)
      }
    }
  },
  computed: {
    // 详细地址
    adds () {
      if (!this.address) return ''
      const { provinceName, cityName, countyName, detailInfo } = this.address
      return provinceName + cityName + countyName + detailInfo
    },
    // 是否全部选中
    isSelAll () {
      return this.seledPrds.length === this.carts.length
    },
    // 选中商品
    seledPrds () {
      return this.carts.filter(cart => cart.goods_checked)
    },
    // 计算选中商品的金额
    amount () {
      let total = 0
      this.seledPrds.forEach(prd => {
        total += prd.goods_price * prd.goods_count
      })
      return total
    }
  },
  // 因为onLoad组件加载只执行一次=》使用onShow保证可以获取到本地最新的购物车数据
  onShow () {
    this.getCarts()
  },
  methods: {
    // 创建订单
    async createOrder () {
      /**
       * 1. 用户选择过收货地址
       * 2. 购物车商品至少选中一个
       * 3. 用户登录
       */
      if (!this.address) {
        return uni.showToast({
          title: '请选择收货地址！',
          duration: 2000
        })
      }
      if (!this.seledPrds.length) {
        return uni.showToast({
          title: '请选择至少选择一个商品结算！',
          icon: 'none',
          duration: 2000
        })
      }
      if (!uni.getStorageSync('token')) {
        // 跳转登录页面
        return uni.navigateTo({
          url: '/packone/auth/index'
        })
      }
      // 调用后台接口=》执行订单创建
      console.log('可以创建订单了！')
      const { msg } = await this.request({
        url: '/api/public/v1/my/orders/create',
        method: 'post',
        data: {
          order_price: this.amount,
          consignee_addr: this.adds,
          goods: this.seledPrds.map(prd => {
            // 拷贝当前遍历的商品
            let _prd = { ...prd }
            //  新增后台需要的字段
            _prd.goods_number = _prd.goods_count
            return _prd
          })
        }
      })
      console.log(msg)
      if (msg.status === 200) {
        /**
         * 创建订单需要有选中的商品=》创建成功以后=》从购物车中移除结算的商品
         */
        /**
         *  1. 获取没有参与结算的商品（保留） 
         *     * 购物车中商品全部结算 =》[]（剁手操作）
         *     * 购物车中商品部分结算 => [没有参与结算商品] 
         *  2. 存储到本地
         */
        let unSeled = this.carts.filter(prd => !prd.goods_checked)
        uni.setStorageSync('carts', unSeled)
        uni.showModal({
          title: '提示',
          content: msg.msg,
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定')
              // 跳转订单列表页
              uni.navigateTo({
                url: '/packone/order/index'
              })
            }
          }
        })
      } else {
        uni.showToast({
          title: msg.msg,
          icon: 'none'
        })
      }

    },
    // 获取收货地址
    async getAddress () {
      const [error, address] = await uni.chooseAddress()
      console.log(error, address)
      if (!error) {
        this.address = address
      }
    },
    // 获取本地缓存中购物车数据
    getCarts () {
      this.carts = uni.getStorageSync('carts') || []
    },
    // 更新购物车数据
    // undateCarts () {
    //   uni.setStorageSync('carts', this.carts)
    // },
    // 单选
    signSel (i) {
      this.carts[i].goods_checked = !this.carts[i].goods_checked
      // this.undateCarts()
    },
    // 全选
    /**
     * 1. 购物车没有全部选择=》全部选中
     * 2. 购物车全部选中=》全部取消选中
     */
    selAll () {
      if (this.isSelAll) {
        this.carts.forEach(prd => prd.goods_checked = false)
      } else {
        this.carts.forEach(prd => prd.goods_checked = true)
      }
    },
    // 购物车商品数量增减
    /**
     * i 当前商品的索引
     * type: 1 代表加  -1 代表减
     */
    changeCount (i, type) {
      /**
       * 1. 处理边界：最小1 库存 10（最大）
       * 2. 正常加减
       * 3. 更新本地缓存
       */
      // 获取当前操作商品的数量
      let count = this.carts[i].goods_count
      let max = 10, min = 1
      if (type === 1 && count >= max) {
        return uni.showToast({
          title: `最大:${max}`,
          duration: 2000
        })
      } else if (type === -1 && count === min) {
        return uni.showToast({
          title: `最小:${min}`,
          duration: 2000
        })
      }
      this.carts[i].goods_count += type
      // this.undateCarts()
    }
  }
};
</script>

<style scoped lang="scss">
.shipment {
  height: 100rpx;
  line-height: 2;
  padding: 30rpx 30rpx 40rpx 30rpx;
  font-size: 27rpx;
  color: #333;
  background-color: #fff;
  background-image: url(http://static.botue.com/ugo/images/cart_border%402x.png);
  background-size: contain;
  background-repeat: no-repeat;
  background-position: bottom;

  .dt {
    width: 140rpx;
    float: left;
    clear: both;
  }

  .dd {
    padding-left: 160rpx;
  }

  .meta {
    padding-right: 50rpx;
  }

  text.phone {
    float: right;
  }
}

.carts {
  background-color: #f4f4f4;
  padding-bottom: 110rpx;
  overflow: hidden;

  .shopname {
    padding: 30rpx;
    margin-top: 20rpx;
    font-size: 30rpx;
    color: #333;
    background-color: #fff;
    border-top: 1rpx solid #eee;
    border-bottom: 1rpx solid #eee;
  }

  .goods {
    display: flex;
    padding: 30rpx 20rpx 30rpx 0;
    margin-left: 100rpx;
    border-bottom: 1rpx solid #eee;
    background-color: #fff;

    position: relative;

    .checkbox {
      width: 101rpx;
      height: 100%;
      background-color: #fff;

      display: flex;
      justify-content: center;
      align-items: center;

      position: absolute;
      left: -100rpx;
      top: 0;
    }

    &:last-child {
      border-bottom: none;
    }

    .pic {
      width: 200rpx;
      height: 200rpx;
      margin-right: 30rpx;
    }

    .meta {
      flex: 1;
      font-size: 27rpx;
      color: #333;
      position: relative;
    }

    .name {
      width: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
    }

    .price {
      position: absolute;
      bottom: 0;

      color: #ea4451;
      font-size: 33rpx;

      text {
        font-size: 22rpx;
      }
    }

    .amount {
      position: absolute;
      bottom: 0;
      right: 20rpx;

      height: 48rpx;
      text-align: center;
      border: 1rpx solid #ddd;
      border-radius: 8rpx;

      display: flex;
      align-items: center;

      text {
        display: block;
        width: 60rpx;
        line-height: 48rpx;
        font-size: 36rpx;
        color: #ddd;
        text-align: center;
      }

      input {
        width: 60rpx;
        height: 48rpx;
        min-height: 48rpx;
        font-size: 27rpx;
        border-left: 1rpx solid #ddd;
        border-right: 1rpx solid #ddd;
      }
    }
  }
}

.extra {
  position: fixed;
  bottom: 0;
  /* #ifdef H5 */
  bottom: 50px;
  /* #endif */
  left: 0;
  z-index: 9;

  width: 750rpx;
  height: 96rpx;
  text-align: center;
  line-height: 96rpx;
  font-size: 36rpx;
  border-top: 1rpx solid #eee;
  background-color: #fff;
  color: #333;
  display: flex;

  .checkall {
    width: 140rpx;
    line-height: 1;
    margin-left: 25rpx;
    display: flex;
    align-items: center;

    icon {
      margin-right: 20rpx;
    }
  }

  .total {
    display: flex;
    justify-content: center;
    flex: 1;

    label,
    text {
      color: #ea4451;
      vertical-align: bottom;
      position: relative;
      bottom: -2rpx;
    }

    text {
      position: relative;
      bottom: -3rpx;
      font-size: 24rpx;

      &:first-child {
        margin-left: 10rpx;
      }
    }
  }

  .pay {
    width: 200rpx;
    background-color: #ea4451;
    color: #fff;
  }
}
</style>

